"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : security-EqualityQuery
Case Name   : 通过JDBC创建CMK，设置参数enable_ce=0
Create At   : 2023/9/26
Owner       : @zou_jialiang050
Description :
    1.拷贝java脚本到主机，写入连接信息
    2.编译脚本
    3.执行脚本
Expect      :
    1.拷贝完成，写入信息成功
    2.编译成功
    3.执行失败
History     :
"""
import os
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Common import Common
from testcase.utils.Logger import Logger


class Equality(unittest.TestCase):
    def setUp(self):
        self.logger = Logger()
        self.logger.info(f'-----{os.path.basename(__file__)} start-----')
        self.sh_primy = CommonSH('PrimaryDbUser')
        self.common = Common()
        self.primary_root = Node(node='PrimaryRoot')
        self.userNode = Node('PrimaryDbUser')
        self.localkms = os.path.join(macro.DB_INSTANCE_PATH, '..', 'app',
                                     'etc', 'localkms')
        self.jdbc_script = os.path.join('/', 'home', 'jdbc_security')
        self.java_name = 'jdbc_secret_equivalence_query_0001'
    
    def test_security(self):
        text = '----pre1:配置$GAUSSHOME/etc/localkms路径;expect:成功---'
        self.logger.info(text)
        mkdir_cmd1 = f'if [ ! -d "{self.localkms}" ];' \
            f'then mkdir {self.localkms};fi'
        self.logger.info(mkdir_cmd1)
        mkdir_msg1 = self.userNode.sh(mkdir_cmd1).result()
        self.assertTrue(mkdir_msg1 == '' or 'File exists' in mkdir_msg1)
        mkdir_cmd2 = f'if [ ! -d "{self.jdbc_script}" ];' \
            f'then mkdir {self.jdbc_script};fi'
        self.logger.info(mkdir_cmd2)
        mkdir_msg2 = self.primary_root.sh(mkdir_cmd2).result()
        self.logger.info(mkdir_msg2)
        self.assertTrue(mkdir_msg2 == '' or 'File exists' in mkdir_msg2)
        
        text = '---step1:拷贝java脚本到主机，写入连接信息;expect:成功---'
        self.logger.info(text)
        jar_name, jar_path = self.common.get_jdbc('postgresql')
        self.primary_root.scp_put(macro.JDBC_PATH,
                        f"{os.path.join(self.jdbc_script, jar_name)}")
        res2 = self.common.scp_file(self.primary_root,
                             f"{self.java_name}.java", self.jdbc_script)
        self.logger.info(res2)
        con_params = [self.primary_root.ssh_host, self.userNode.db_port,
                      self.userNode.db_name, self.userNode.db_user,
                      self.userNode.db_password, 'enable_ce=0']
        replace_content = ['host_ip', 'db_port', 'database_name',
                           'conn_user', 'conn_passwd', 'url_params']
        i = 0
        while i < len(replace_content):
            exe_cmd1 = f"sed -i 's/{replace_content[i]}/{con_params[i]}/g' " \
                f"{os.path.join(self.jdbc_script, f'{self.java_name}.java')}"
            self.logger.info(exe_cmd1)
            msg1 = self.primary_root.sh(exe_cmd1).result()
            self.logger.info(msg1)
            self.assertEqual('', msg1, '执行失败' + text)
            i += 1
        check_cmd = f"cat " \
            f"{os.path.join(self.jdbc_script, f'{self.java_name}.java')}"
        check_msg = self.primary_root.sh(check_cmd).result()
        for content in con_params:
            self.assertIn(content, check_msg, '执行失败' + text)
            
        text = '---step2:编译脚本;expect:成功---'
        self.logger.info(text)
        exe_cmd2 = f"javac -encoding utf-8 -cp " \
            f"{os.path.join(self.jdbc_script, jar_name)} " \
            f"{os.path.join(self.jdbc_script, f'{self.java_name}.java')}"
        self.logger.info(exe_cmd2)
        msg2 = self.primary_root.sh(exe_cmd2).result()
        self.logger.info(msg2)
        self.assertEqual('', msg2, '执行失败:' + text)

        text = '---step3:执行脚本;expect:失败---'
        self.logger.info(text)
        exe_cmd3 = f"source {macro.DB_ENV_PATH};java -cp " \
            f"{os.path.join(self.jdbc_script, jar_name)}:" \
            f"{os.path.join(self.jdbc_script, f'{self.jdbc_script}.jar')}:" \
            f"{self.jdbc_script} {self.java_name}"
        self.logger.info(exe_cmd3)
        msg3 = self.primary_root.sh(exe_cmd3).result()
        self.logger.info(msg3)
        self.assertIn('Un-support to drop client master key when client '
                      'encryption is disabled', msg3, '执行失败:' + text)
    
    def tearDown(self):
        text = '----清理环境----'
        self.logger.info(text)
        clean_cmd = f'rm -rf {self.localkms};rm -rf {self.jdbc_script};' \
            f'ls {self.localkms};ls {self.jdbc_script}'
        clean_msg = self.primary_root.sh(clean_cmd).result()
        self.logger.info(clean_msg)
        self.assertTrue(clean_msg.count('No such file or directory') == 2,
                        text + '执行失败')
        self.logger.info(f'-----{os.path.basename(__file__)} end-----')
